# Copyright (c) 2009 Olexandr Melnyk <me@omelnyk.net>
# See COPYING for details.

import re
import urllib
import urllib2

# Translation interface for reta-vortaro.de
class RetaVortaroDictionary:
    # Constructor
    def __init__(self):
        self.short_name = "revo"
        self._search_url = 'http://www.reta-vortaro.de/cgi-bin/sercxu.pl'
        self._word_url   = 'http://www.reta-vortaro.de/revo/art/%s.html'

    # Returns list of roots, from which the specified word can be formed
    def find_related_roots(self, word):
        vals = { 'sercxata' : word }
        data = urllib.urlencode(vals)
        req  = urllib2.Request(self._search_url, data)
        html = urllib2.urlopen(req).read()

        pattern = '(<a target="precipa" href="/revo/art/)([^<]+)(.html#)([^>]*)(">)([^<]+)(<\/a>)'
        results = re.findall(pattern, html)

        return [res[1] for res in results if res[3] != 'lng_']

    # Returns translation of the specified word (containing the specified root),
    # from source_lang to target_lang
    def get_translations(self, root, word, source_lang, target_lang):
        req  = urllib2.Request(self._word_url % root)
        html = urllib2.urlopen(req).read()
        
        pattern = '(<a name="lng_)([^<]+)("><\/a>)(<h3[^<]*>)([^<]+)(<\/h3>)(<span class="trdeo">)(<a[^>]+>~)([^<]+)(:[^<]+)(<\/a>)([^<]*)(<\/span>)(\s+)(<span class="trdnac">)([^<]+)(<\/span>)'
        results = re.findall(pattern, html)

        trans = []
        for res in results:
            if res[1] == target_lang and root + res[8] == word:
               trans.append(res[15])
            elif res[1] == source_lang and res[15] == word:
               trans.append(root + res[8])

        return [t.strip() for t in trans]

    # Returns list of supported language pairs
    def supported_pairs(self):
        return [("en", "eo"), ("eo", "en"), ("sv", "eo"), ("eo", "sv")]
    
    # Translates word from source_lang to target_lang
    def translate(self, word, source_lang, target_lang):
        roots = self.find_related_roots(word)

        trans = []        
        for root in roots:
            tmp = self.get_translations(root, word, source_lang, target_lang)
            trans.extend(tmp)

        return list(set(trans))
